package com.kll.tv.views

import android.content.Intent
import android.graphics.Color
import android.os.Bundle
import android.view.Gravity
import android.view.View
import androidx.recyclerview.widget.GridLayoutManager
import com.google.gson.Gson
import com.kll.carolinehmibiz.OperationManager
import com.kll.carolinehmibiz.model.AccountModel
import com.kll.carolinehmibiz.model.OperateListener
import com.kll.carolinehmibiz.net.bean.AddPhoto
import com.kll.carolinehmibiz.net.bean.GetPhotoAlbumResponse
import com.kll.carolinehmibiz.net.bean.RefreshTokenResponse
import com.kll.carolinehmibiz.presentation.listener.PhotoAlbumLovelyProtocol
import com.kll.carolinehmibiz.presentation.presenter.PhotoAlbumLovelyPresenter
import com.kll.tv.R
import com.kll.tv.base.views.BaseActivity
import com.kll.tv.databinding.ActivityPhotoAlbumLovelyBinding
import com.kll.tv.utils.AppToast
import com.kll.tv.utils.GlideEngine
import com.kll.carolinehmibiz.base.utils.L
import com.kll.tv.utils.PopWindow
import com.kll.tv.views.adapter.PersonalAvatarPopAdapter
import com.kll.tv.views.adapter.PhotoSlbumLovelyAdapter
import com.luck.picture.lib.PictureSelector
import com.luck.picture.lib.config.PictureConfig
import com.luck.picture.lib.config.PictureMimeType
import com.luck.picture.lib.entity.LocalMedia
import com.luck.picture.lib.listener.OnResultCallbackListener

/**
 * ====================================================
 * Created by Ziliang Cai on 2022/01/11 15:13
 * <a href="mailto:752577456@qq.com">Contact me</a>
 * ====================================================
 */
class PhotoAlbumLovelyActivity: BaseActivity<PhotoAlbumLovelyPresenter>(), PhotoAlbumLovelyProtocol.IView,
PhotoSlbumLovelyAdapter.OnPhotoListItemClickListener {
    private lateinit var binding: ActivityPhotoAlbumLovelyBinding
    private var adapter: PhotoSlbumLovelyAdapter? = null
    private var popAvatarWindow: PopWindow? = null
    private var personalAvatarPopAdapter: PersonalAvatarPopAdapter? = null
    private var dataList: ArrayList<Any> = arrayListOf()
    private var photoUrlList: ArrayList<String> = arrayListOf()
    private var photoList: ArrayList<GetPhotoAlbumResponse.PhotoAlbum.PhotoInfo> = arrayListOf()
    private var isManageWork = false // false-取消管理作品 true-管理作品
    private var isAllChecked = false // 是否全选

    override fun initViewBinding(): View {
        binding = ActivityPhotoAlbumLovelyBinding.inflate(layoutInflater)
        return binding.root
    }

    override fun createPresenter(): PhotoAlbumLovelyPresenter {
        return PhotoAlbumLovelyPresenter(this, this)
    }

    override fun init() {
        // 初始化adapter
        if (adapter == null) {
            val gridLayoutManager = GridLayoutManager(this, 6)
            gridLayoutManager.orientation = GridLayoutManager.VERTICAL
            binding.rcvPhoto.layoutManager = gridLayoutManager
            adapter = PhotoSlbumLovelyAdapter(this)
            binding.rcvPhoto.adapter = adapter
            adapter!!.setOnPhotoListItemClickListener(this)
        }

        initData()
        initListener()

    }

    private fun initData() {
        mPresenter.loadPhotoDatas(true)
    }

    private fun initListener() {
        binding.ivBack.setOnClickListener {
            finish()
        }
        // 添加图片
        binding.tvUpload.setOnClickListener {
            toShowAvatarPop()
        }
        // 编辑图片
        binding.tvEdit.setOnClickListener {
            if (isManageWork) {
                isManageWork = !isManageWork
                binding.tvEdit.text = "编辑"
                binding.llEditPhoto.visibility = View.GONE
            } else {
                isManageWork = !isManageWork
                binding.tvEdit.text = "取消"
                binding.llEditPhoto.visibility = View.VISIBLE
            }
            isAllChecked = false
            binding.tvAll.text = "全选"
            binding.tvDelete.setTextColor(Color.parseColor("#000000"))
            adapter?.setIsEdit(isManageWork)
        }
        // 是否全选
        binding.tvAll.setOnClickListener {
            isAllChecked = !isAllChecked
            binding.tvAll.text = if (isAllChecked) "不全选" else "全选"
            adapter?.setAllChecked(isAllChecked)
            onItemCheckClickListener()
        }
        // 删除作品
        binding.tvDelete.setOnClickListener {
            val checkeds: ArrayList<Int> = adapter!!.getChecksArray()
            if (checkeds.size > 0) {
                mPresenter.delPhoto(checkeds)
            } else {
                AppToast.show("请选择再操作！", 2000)
            }
        }
    }

    // 弹窗
    private var toShowAvatarPopIsBusying = false
    private fun toShowAvatarPop() {
        if (toShowAvatarPopIsBusying) return
        toShowAvatarPopIsBusying = true

        if (popAvatarWindow == null) {
            popAvatarWindow = PopWindow(this)
            personalAvatarPopAdapter = PersonalAvatarPopAdapter(this,
                View.OnClickListener { v ->
                    when(v.id) {
                        R.id.tv_photograph -> {
                            // 拍照
                            AppToast.show("拍摄", 2000)
                            getAndroidQCamera()
                        }
                        R.id.tv_from -> {
                            // 从电视选择
                            AppToast.show("从相册选择", 2000)
                            getAndroidQImage()
                        }
                        R.id.tv_cancel -> {
                            // 取消
                            AppToast.show("取消", 2000)
                        }
                    }
                    popAvatarWindow!!.dismiss()
                })
            popAvatarWindow!!.addView(personalAvatarPopAdapter)
            popAvatarWindow!!.animationStyle = R.style.popwindow_anim_style
        }
        popAvatarWindow!!.showAtLocation(binding.root, Gravity.BOTTOM, 0, 0)
        toShowAvatarPopIsBusying = false
    }

    /**
     * 适配AndroidQ的相册获取
     */
    private fun getAndroidQImage() {
        PictureSelector.create(this)
            .openGallery(PictureMimeType.ofImage()) // 全部-ofAll 图片-ofImage 视频-ofVideo 音频-ofAudio
            .loadImageEngine(GlideEngine.createGlideEngine())
            .isWeChatStyle(true)
            .maxSelectNum(9) // 最大图片选择数量
            .minSelectNum(1) // 最小图片选择数量
            .compress(false)
            .minimumCompressSize(1024)
            .imageSpanCount(4) // 每行显示个数
            .isReturnEmpty(false) // 未选择数据时点击按钮是否可以返回
            .selectionMode(PictureConfig.MULTIPLE) // 多选 or 单选
            .forResult(object : OnResultCallbackListener<LocalMedia> {
                override fun onResult(result: MutableList<LocalMedia>?) {
                    if (result != null && result.size > 0) {
                        addPhoto(result)
                    }
                }

                override fun onCancel() {
                    AppToast.show("操作已取消！", 2000)
                }

            })
    }

    /**
     * 拍照
     */
    private fun getAndroidQCamera() {
        PictureSelector.create(this)
            .openCamera(PictureMimeType.ofImage())
            .loadImageEngine(GlideEngine.createGlideEngine())
            .isAndroidQTransform(true)
            .isUseCustomCamera(true)
            .isCameraAroundState(true)
            .forResult(object : OnResultCallbackListener<LocalMedia> {
                override fun onResult(result: MutableList<LocalMedia>?) {
                    if (result != null && result.size != 0) {
                        addPhoto(result)
                    }
                }

                override fun onCancel() {
                    AppToast.show("操作已取消！", 2000)
                }

            })
    }

    /**
     * 处理数据后添加图片
     */
    private fun addPhoto(data: MutableList<LocalMedia>) {
        val list = arrayListOf<AddPhoto.Photo>()
        for (i in data) {
            val photo = AddPhoto.Photo()
            photo.url = i.path
            list.add(photo)
        }

        mPresenter.addPhoto(list)
    }

    /**
     * 获取图片列表成功回调
     */
    override fun loadPhotoDataSuccessed(datas: ArrayList<GetPhotoAlbumResponse.PhotoAlbum>) {
        // 处理数据
        dataList.clear()
        photoList.clear()
        photoUrlList.clear()
        for (i in datas) {
            dataList.add(i.title)
            for (j in i.datas!!) {
                dataList.add(j)
                photoList.add(j)
                photoUrlList.add(j.url)
            }
        }

        adapter!!.photoData = photoList
        adapter!!.photoUrlData = photoUrlList
        adapter!!.data = dataList
    }

    /**
     * 获取图片列表失败回调
     */
    override fun loadPhotoDataFailed(code: Int, message: String) {
        AppToast.show(message, 2000)
        if (code == 102) {
            // token过期 刷新token
            OperationManager.getInstancce().refreshToken(object : OperateListener {
                override fun onSuccess(state: Int, obj: Any?) {
                    var data = obj as RefreshTokenResponse
                    AccountModel.getInstance(baseContext).updateUserToken(data.token)
                    mPresenter.loadPhotoDatas(true)
                }

                override fun onFail(code: Int, message: String) {
                    AppToast.show(message, 2000)
                    if (code == 101) {
                        loginAgain()
                    }
                }

            })
        }
        if (code == 101) {
            loginAgain()
        }
    }

    /**
     * 添加图片成功回调
     */
    override fun addPhotoSuccessed() {
        initData()
    }

    /**
     * 添加图片失败回调
     */
    override fun addPhotoFailed(code: Int, message: String) {
        AppToast.show(message, 2000)
        if (code == 102) {
            // token过期 刷新token
            OperationManager.getInstancce().refreshToken(object : OperateListener {
                override fun onSuccess(state: Int, obj: Any?) {
                    var data = obj as RefreshTokenResponse
                    AccountModel.getInstance(baseContext).updateUserToken(data.token)
                    mPresenter.loadPhotoDatas(true)
                }

                override fun onFail(code: Int, message: String) {
                    AppToast.show(message, 2000)
                    if (code == 101) {
                        loginAgain()
                    }
                }

            })
        }
        if (code == 101) {
            loginAgain()
        }
    }

    /**
     * 删除图片成功回调
     */
    override fun delPhotoSuccessed() {
        initData()
    }

    /**
     * 删除图片失败回调
     */
    override fun delPhotoFailed(code: Int, message: String) {
        AppToast.show(message, 2000)
        if (code == 102) {
            // token过期 刷新token
            OperationManager.getInstancce().refreshToken(object : OperateListener {
                override fun onSuccess(state: Int, obj: Any?) {
                    var data = obj as RefreshTokenResponse
                    AccountModel.getInstance(baseContext).updateUserToken(data.token)
                    mPresenter.loadPhotoDatas(true)
                }

                override fun onFail(code: Int, message: String) {
                    AppToast.show(message, 2000)
                    if (code == 101) {
                        loginAgain()
                    }
                }

            })
        }
        if (code == 101) {
            loginAgain()
        }
    }

    /**
     * item点击回调
     */
    override fun onPhotoItemClick(data: GetPhotoAlbumResponse.PhotoAlbum.PhotoInfo) {
        var position = 0
        for (i in 0..(photoUrlList.size - 1)) {
            if (photoUrlList[i] == data.url) {
                position = i
            }
        }

        // 点击了图片
        val intent = Intent(this, ImageReviewActivity::class.java)
        val bundle = Bundle()
        val photos = photoUrlList
        bundle.putSerializable("data", photos)
        intent.putExtra("data", bundle)
        intent.putExtra("index", position)
        startActivity(intent)
    }

    /**
     * 编辑状态下点击item回调
     */
    override fun onItemCheckClickListener() {
        val checkeds = adapter!!.getChecksArray()
        L.d("TAG", "initListener: ${Gson().toJson(checkeds)}")
        binding.tvDelete.isClickable = checkeds.size > 0
    }


}